package com.hxl.linuxfilemanager.service.impl;

import com.alibaba.fastjson.JSON;
import com.hxl.linuxfilemanager.config.LinuxPropertiesConfig;
import com.hxl.linuxfilemanager.entity.FileEntity;
import com.hxl.linuxfilemanager.service.IFileService;
import com.hxl.linuxfilemanager.util.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class FileServiceImpl implements IFileService {
    private static final String FOLDER_PATH = "/static/imgs/ic-folder.png";
    private static final String FILE_PATH = "/static/imgs/ic-file.png";
    private static final String BASE_PATH = "/static/imgs/ic-{type}.png";


    @Autowired
    LinuxPropertiesConfig linuxPropertiesConfig;


    @Autowired
    ResourceLoader resourceLoader;

    @Override
    public List<FileEntity> listFile(String parentPath) {
        List<FileEntity> result = new ArrayList<>();

        List<File> files = FileUtils.listFile(parentPath);
        for (File file : files) {
            result.add(createFileEntity(file));
        }
        return result;
    }

    public FileEntity createFileEntity(File file) {
        FileEntity fileEntity = new FileEntity(file.getName(), file.isFile() ? file.length() : 0, file.getAbsolutePath(), file.isFile());
        /**
         * 如果是文件
         */
        if (file.isFile()) {
            String type = file.getName();
            int spotIndex = type.lastIndexOf(".");
            /**
             * 所有有扩展名
             */
            if (spotIndex > -1 && (type.length() - (spotIndex + 1) != 0)) {
                String extend = type.substring(type.lastIndexOf(".") + 1);
                Resource resource = resourceLoader.getResource("classpath:static/imgs/ic-" + extend + ".png");
                /**
                 * 如果扩展名存在
                 */
                if (resource.exists()) {
                    fileEntity.setExtendImage(BASE_PATH.replace("{type}", extend));
                } else {
                    fileEntity.setExtendImage(FILE_PATH);
                }
            } else {
                fileEntity.setExtendImage(FILE_PATH);
            }
            /**
             * 不是文件
             */
        } else {
            fileEntity.setExtendImage(FOLDER_PATH);
        }

        return fileEntity;
    }

    @Override
    public boolean saveFile(InputStream inputStream, String path) throws IOException {
        IOUtils.copy(inputStream, new FileOutputStream(new File(path)));
        return true;
    }

    @Override
    public String markFile(String path, boolean isMark) {

        String markFilePath = linuxPropertiesConfig.getDataPath() + "/" + linuxPropertiesConfig.getMarkName();

        /**
         * 读取文件，不存在则创建后返回默认
         */
        String s = FileUtils.readFileData(markFilePath, "[]");
        List<String> list = JSON.parseArray(s, String.class);
        /**
         * 如果指令是收藏
         */
        if (isMark) {
            /**
             * 如果没收藏
             */
            if (!list.contains(path)) {
                list.add(path);
                FileUtils.writeDataToFile(markFilePath, JSON.toJSONString(list));
                return "收藏成功";
            }else {
                return "该文件已经收藏";
            }
        } else {
            if (list.contains(path)){
                list.remove(path);
                FileUtils.writeDataToFile(markFilePath, JSON.toJSONString(list));
                return "取消收藏成功";
            }
            return "改文件不存在，无法取消收藏";

        }

    }

    @Override
    public List<FileEntity> listMarkFile() {
        String markFilePath = linuxPropertiesConfig.getDataPath()+ "/" + linuxPropertiesConfig.getMarkName();

        String s = FileUtils.readFileData(markFilePath, "[]");
        List<String> list = JSON.parseArray(s, String.class);
        List<FileEntity> result = new ArrayList<>();

        list.stream().forEach(item->{
            File file =new File(item);
            result.add(createFileEntity(file));
        });

        return result;
    }
}
